<template>
  <div class="wechat_config">
    <!--<div class="before-begin" v-if="currentType === 'begin'">-->
      <!--<div class="wechat-logo">-->
        <!--<img src="../../../../../assets/img/weChatLogo.png" alt=""/>-->
        <!--<span>-->
                    <!--<p>-->
                      <!--只需将您的微信公众号绑定到客服系统,<br/>就可以轻松处理来自微信公众号用户的咨询。-->
                    <!--</p>-->
                <!--</span>-->
      <!--</div>-->
      <!--<p>微信公众号需要是服务号或者订阅号</p>-->
      <!--<el-button type="primary" class="primary_btn" @click="currentType = 'chooseType'">绑定微信客服</el-button>-->
    <!--</div>-->
    <div class="bindChoose" v-if="currentType === 'chooseType'">
      <div class="title">{{$t('configLazyLoad.channel.wexinTip1')}}</div>
      <div class="wechatType">
        <div class="wechatoption" style="margin-right: 30px">
          <el-radio label="wechatAuth" v-model="choosewechatType" class="font18">{{$t('configLazyLoad.channel.wexinTip2')}}</el-radio>
          <p>{{$t('configLazyLoad.channel.wexinTip3')}}</p>
        </div>
        <div class="wechatoption">
          <el-radio label="wechatDock" v-model="choosewechatType" class="font18">{{$t('configLazyLoad.channel.wexinTip4')}}</el-radio>
          <p>{{$t('configLazyLoad.channel.wexinTip5')}}</p>
        </div>
        <div class="wechatoption">
          <el-radio label="wechatPlatform" v-model="choosewechatType" class="font18">{{$t('configLazyLoad.channel.wexinTip6')}}</el-radio>
          <p>{{$t('configLazyLoad.channel.wexinTip7')}}</p>
        </div>
      </div>
      <div style="margin: 20px">
        <el-button class="primary_btn" style="margin-right: 20px" @click="cancelType">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click="confirmType">{{$t('public.confirm')}}</el-button>
      </div>
    </div>
    <wechat-dock v-if="currentType === 'wechatDock'" @cancel="reset"></wechat-dock>
    <wechat-auth v-if="currentType === 'wechatAuth'" @reset="reset"></wechat-auth>
    <wechatPlatform v-if="currentType === 'wechatPlatform'" @cancel="reset"></wechatPlatform>
    <div class="base-content" v-if="currentType === 'wechatManage'">
      <div class="before-begin">
        <div class="wechat-logo">
          <img src="../../../../../assets/img/weChatLogo.png" alt=""/>
          <span>
                    <p>
                      {{$t('configLazyLoad.channel.wexinTip8')}}<br/>
                      {{$t('configLazyLoad.channel.wexinTip08')}}
                    </p>
                </span>
        </div>
        <p>{{$t('configLazyLoad.channel.wexinTip9')}}</p>
        <el-button type="primary" class="primary_btn" @click="currentType = 'chooseType'">{{$t('configLazyLoad.channel.wexinTip10')}}</el-button>
      </div>
      <search :isShowInput="false"
              :isReloadIvr="false"
              :showAdvSearch="false"
              @add="add"
              @refresh="refresh"
              @turnPage="turnPage"
              :currentPage="currentPage"
              :count="count"
              :pageSize="pageSize"
          >
          <el-radio-group v-model="wechatType">
            <el-radio label="wechatAuthorization">{{$t('config.channel.wechatAuthorization')}}</el-radio>
            <el-radio label="wechatDocking">{{$t('config.channel.wechatDocking')}}</el-radio>
            <el-radio label="wechatPlatformDocking">{{$t('config.channel.wechatPlatformDocking')}}</el-radio>
          </el-radio-group>
      </search>
      <el-table :data="tableData" size="mini">
          <el-table-column prop="nick_name" :label="$t('configLazyLoad.channel.wechatName')">
          </el-table-column>
          <el-table-column prop="to_peer_name" :label="$t('public.queues')">
          </el-table-column>
          <el-table-column prop="robotname" :label="$t('config.channel.isUseRobt2')">
          </el-table-column>
          <el-table-column :label="$t('configLazyLoad.channel.wexinTip12')">
            <template scope="scope">
              <span v-if="wechatType === 'wechatAuthorization'">{{$t('configLazyLoad.channel.wexinTip2')}}</span>
              <span v-if="wechatType === 'wechatDocking'">{{$t('configLazyLoad.channel.wexinTip4')}}</span>
              <span v-if="wechatType === 'wechatPlatformDocking'">{{$t('configLazyLoad.channel.wexinTip6')}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="lastUpdateTime" :label="$t('configLazyLoad.channel.wexinTip11')" v-if="wechatType === 'wechatAuthorization'">
          </el-table-column>
          <el-table-column :label="$t('public.operate')">
            <template scope="scope">
              <el-button @click="modify(scope.row)" type="text" size="small" class="update">{{$t('public.edit')}}</el-button>
              <el-button type="text" @click="delrow(scope.row)" size="small" class="del">{{$t('public.delete')}}</el-button>
            </template>
          </el-table-column>
      </el-table>
    </div>
    <wechat-modify v-if="currentType === 'wechatModify'" :type="modifyType" :data="modifyData" @back="backToManage"></wechat-modify>
  </div>
</template>
<script>
  import Agent from '@/components/public-modules/cache/Agent'
  import search from '../base/search.vue'
  import { getCacheByKey } from '@/utils/m7Utils.js'
  import wechatModify from './wechatModify.vue'
  import wechatDock from './wechatDockStep.vue'
  import wechatAuth from './wechatAuthStep.vue'
  import wechatPlatform from './wechatPlatformAdd.vue'
  export default {
    name: 'wechatManage',
    data () {
      return {
        currentType: 'wechatManage',
        tableData: [],
        choosewechatType: 'wechatAuth',
        wechatType: 'wechatAuthorization',
        currentPage: 1,
        pageSize: 10,
        count: 0,
        modifyType: '',
        modifyData: ''
      }
    },
    watch: {
      wechatType () {
        this.currentPage = 1
        this.fetchData()
      }
    },
    methods: {
      backToManage () {
        this.currentType = 'wechatManage'
        this.fetchData()
      },
      reset () {
        this.currentType = 'wechatManage'
        this.choosewechatType = 'wechatAuth'
        this.fetchData()
      },
      cancelType () {
        this.currentType = 'wechatManage'
        this.choosewechatType = 'wechatAuth'
      },
      confirmType () {
        if (this.choosewechatType === 'wechatAuth') {
          this.currentType = 'wechatAuth'
        } else if (this.choosewechatType === 'wechatDock') {
          this.currentType = 'wechatDock'
        } else if (this.choosewechatType === 'wechatPlatform') {
          this.currentType = 'wechatPlatform'
        }
      },
      delrow (row) {
        if (this.wechatType === 'wechatAuthorization') {
          this.$confirm(this.$t('configLazyLoad.channel.wexinTip13'), this.$t('public.delete'), {
            confirmButtonText: this.$t('public.delete'),
            cancelButtonText: this.$t('public.cancel'),
            cancelButtonClass: 'primary_btn',
            confirmButtonClass: 'primary_btn',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('DeleteWeChatAuth', {_id: row._id}).then((req) => {
              if (req.success) {
                this.$message.success(this.$t('configLazyLoad.public.deleteSuccess'))
                this.fetchData()
              }
            })
          })
        } else if (this.wechatType === 'wechatDocking') {
          this.$confirm(this.$t('configLazyLoad.channel.wexinTip14'), this.$t('public.delete'), {
            confirmButtonText: this.$t('public.delete'),
            cancelButtonText: this.$t('public.cancel'),
            cancelButtonClass: 'primary_btn',
            confirmButtonClass: 'primary_btn',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('DeleteWeChatDock', {_id: row._id}).then((req) => {
              if (req.success) {
                this.$message.success(this.$t('configLazyLoad.public.deleteSuccess'))
                this.fetchData()
              }
            })
          })
        } else if (this.wechatType === 'wechatPlatformDocking') {
          this.$confirm(this.$t('configLazyLoad.channel.wexinTip15'), this.$t('public.delete'), {
            confirmButtonText: this.$t('public.delete'),
            cancelButtonText: this.$t('public.cancel'),
            cancelButtonClass: 'primary_btn',
            confirmButtonClass: 'primary_btn',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('removeWxDevModeConfig', {_id: row._id}).then((req) => {
              if (req.success) {
                this.$message.success(this.$t('configLazyLoad.public.deleteSuccess'))
                this.fetchData()
              }
            })
          })
        }
      },
      add () {
        // this.$emit('add')
        this.currentType = 'chooseType'
      },
      refresh () {
        this.currentPage = 1
        this.fetchData()
      },
      turnPage (val) {
        this.currentPage = val
        this.fetchData()
      },
      fetchData: function () {
        this.tableData = []
        if (this.wechatType === 'wechatAuthorization') {
          this.$store.dispatch('queryWeChatAuthorizationList', {page: this.currentPage, limit: 10}).then((resp) => {
            this.count = resp.count
            let p1 = this.$store.dispatch('getCache', {type: 'mailQueues'})
            let p2 = this.$store.dispatch('getCache', {type: 'robotConfig'})
            let p3 = this.$store.dispatch('queryM7AIRobot', {})
            Promise.all([p1, p2, p3]).then(([a, b, c]) => {
              console.log(a[1], b, c)
              let totalRobot = []
              let m7Robot = b || []
              let aiRobots = []
              if (c.success && c.data && c.data.length > 0) {
                aiRobots = c.data
                aiRobots.forEach((item) => {
                  item._id = item.Id
                  item.robot_type = item.Nick
                })
              }
              totalRobot = m7Robot.concat(aiRobots)
              resp.list && resp.list.length > 0 && resp.list.forEach((item, index) => {
                resp.list[index].wechatUrl = resp.wechatUrl
                let peer = getCacheByKey('mailQueues', 'Exten', item.to_peer)
                if (peer) {
                  resp.list[index]['to_peer_name'] = peer.DisplayName
                }
                if (item.agentUpdateTime) {
                  item.lastUpdateTime = item.agentUpdateTime
                } else {
                  item.lastUpdateTime = item.last_update_time
                }
                if (item.robot) {
                  if (totalRobot.length > 0) {
                    let robot = totalRobot.find((robot1) => { return robot1._id === item.robot })
                    resp.list[index]['robotname'] = robot && robot.robot_type
                  }
                  // let robot = getCacheByKey('robotConfig', '_id', item.robot)
                  // if (robot) {
                  //   resp.list[index]['robotname'] = robot.robot_type
                  // }
                } else {
                  resp.list[index]['robotname'] = this.$t('config.channel.noUsed')
                }
              })
              this.tableData = resp.list
            })
          })
        } else if (this.wechatType === 'wechatDocking') {
          this.pageSize = 10
          let data = {
            platform: 'web',
            page: this.currentPage,
            limit: this.pageSize
          }
          this.$store.dispatch('queryWeChatDockList', data).then((resp) => {
            this.count = resp.count
            let p1 = this.$store.dispatch('getCache', {type: 'mailQueues'})
            let p2 = this.$store.dispatch('getCache', {type: 'robotConfig'})
            Promise.all([p1, p2]).then((a, b) => {
              resp.list && resp.list.forEach((item, index) => {
                let peer = getCacheByKey('mailQueues', 'Exten', item.to_peer)
                if (peer) {
                  resp.list[index]['to_peer_name'] = peer.DisplayName
                }
                if (item.robot) {
                  let robot = getCacheByKey('robotConfig', '_id', item.robot)
                  if (robot) {
                    resp.list[index]['robotname'] = robot.robot_type
                  }
                } else {
                  resp.list[index]['robotname'] = this.$t('config.channel.noUsed')
                }
              })
              this.tableData = resp.list
            })
          })
//          查询微信公众平台对接列表
        } else if (this.wechatType === 'wechatPlatformDocking') {
          this.pageSize = 10
          let data = {
            page: this.currentPage,
            pageSize: this.pageSize
          }
          this.$store.dispatch('getWxDevModeConfigs', data).then((resp) => {
            this.count = resp.count
            let p1 = this.$store.dispatch('getCache', {type: 'mailQueues'})
            let p2 = this.$store.dispatch('getCache', {type: 'robotConfig'})
            Promise.all([p1, p2]).then((a, b) => {
              resp.list && resp.list.forEach((item, index) => {
                let peer = getCacheByKey('mailQueues', 'Exten', item.to_peer)
                if (peer) {
                  resp.list[index]['to_peer_name'] = peer.DisplayName
                }
                if (item.robot) {
                  let robot = getCacheByKey('robotConfig', '_id', item.robot)
                  if (robot) {
                    resp.list[index]['robotname'] = robot.robot_type
                  }
                } else {
                  resp.list[index]['robotname'] = this.$t('config.channel.noUsed')
                }
              })
              this.tableData = resp.list
            })
          })
        }
      },
      modify (row) {
        this.$store.dispatch('getCache', { type: 'mailQueues' }).then(req => {
          let mailQueues = req
          if (!mailQueues || mailQueues.length === 0) {
            this.$message.error(this.$t('configLazyLoad.channel.robotError4'))
            return
          }
          if (this.wechatType === 'wechatDocking') {
            this.modifyType = 'Dock'
            this.modifyData = row
            this.currentType = 'wechatModify'
          } else if (this.wechatType === 'wechatAuthorization') {
            this.modifyType = 'Auth'
            this.modifyData = row
            this.currentType = 'wechatModify'
          } else if (this.wechatType === 'wechatPlatformDocking') {
            this.modifyType = 'Platform'
            this.modifyData = row
            this.currentType = 'wechatModify'
          }
        })
      }
    },
    components: {
      search,
      Agent,
      wechatDock,
      wechatAuth,
      wechatPlatform,
      wechatModify
    },
    mounted () {
      this.fetchData()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .new-config
    .base-content
      height: calc(100vh - 52px);
  .base-content
    height: calc(100vh - 170px);
    overflow-y: auto;
  .update
    cursor pointer
  .el-table .cell >.el-button--text.del
    color $c-pink
    cursor pointer
  .before-begin
    text-align center
    margin 25px
    background #f2f6fa
    >p
      margin-bottom 34px
      font-size 14px
      line-height 18px
    .el-button
      margin-bottom 28px
    .wechat-logo
      padding 34px 0 10px 0
      display table
      margin 0 auto
      span
        display table-cell
        vertical-align middle
        margin-left 10px
        p
          line-height 1.8
          margin-left 14px
          text-align left
  .bindChoose
    text-align center
    margin 25px
    padding 20px
    background #f2f6fa
    text-align center
    .title
      font-size 24px
      font-weight 700px
      margin 20px 0
    .wechatType
      padding 20px
      text-align: center
      .wechatoption
        text-align left
        width 180px
        display inline-block
        vertical-align top
        p
          color $cf-gray4
          padding-left 20px
</style>




















